from django.shortcuts import render, redirect
from django.http import HttpResponse, JsonResponse
from web.forms.project import ProjectModelForm
from web import models
from utils.tencent.cos import create_bucket
import time
def project_list(request):
    """项目列表"""
    if request.method == "GET":
        # 展示项目
        """
        1、从数据库中获取两部分数据
            - 我创建的所有项目：已星标，未星标
            - 我参与的所有项目：已星标，未星标
        2、提取已星标
            - 循环“我创建的所有项目”和“我参与的所有项目”，获取已星标的数据
        得到三个列表：星标、创建、参数
        """
        project_dict = {"star_project": [], "my_project": [], "join_project": []}
        my_project_list = models.Project.objects.filter(creator=request.tracer.user).all()
        join_project_list = models.ProjectUser.objects.filter(user=request.tracer.user).all()
        for row in my_project_list:
            if row.star:
                project_dict["star_project"].append({"value": row, "type": "my"})
            else:
                project_dict["my_project"].append(row)
        for item in join_project_list:
            if item.star:
                project_dict["star_project"].append({"value": item.project, "type": "join"})
            else:
                project_dict["join_project"].append(item.project)
        form = ProjectModelForm(request,)
        return render(request, "project_list.html", {"form": form, "project_dict": project_dict})
    form = ProjectModelForm(request, data=request.POST)
    if form.is_valid():
        # 提交之前创建桶
        # 桶名不能重复 “{项目名}-{手机号}-{时间戳}-{后缀}”
        title = form.cleaned_data.get("title")
        bucket = "{}-{}-{}-1304881545".format(title, request.tracer.user.mobile_phone, str(int(time.time())), )
        print(bucket)
        region = "ap-chengdu"
        # 在腾讯云中创建一个桶，为每一个项目创建一个
        create_bucket(bucket, region)
        # 在数据库中创建bucket 和 region 字段
        form.instance.bucket = bucket
        form.instance.region = region
        # 用户只提交了项目名，颜色，描述
        # 还得加上是谁创建的，必须子在保存之前赋值
        form.instance.creator = request.tracer.user
        instance = form.save()  # 创建项目

        # 2. 创建问题类型
        issue_type_list = []
        for item in models.IssueType.ISSUE_TYPE_LIST:  # ["问题", "任务", "Bug"]
            issue_type_list.append(models.IssueType(project=instance, title=item))
        #  批量创建
        models.IssueType.objects.bulk_create(issue_type_list)

        return JsonResponse({"status": True})
    return JsonResponse({"status": False, "error": form.errors})


def project_star(request, project_type, project_id):
    """星标项目"""
    if project_type == "my":
        models.Project.objects.filter(id=project_id, creator=request.tracer.user).update(star=True)
        return redirect("web:project_list")
    if project_type == "join":
        models.ProjectUser.objects.filter(project_id=project_id, creator=request.tracer.user).update(star=True)
        return redirect("web:project_list")
    return HttpResponse("请求错误")

def project_unstar(request, project_type, project_id):
    """取消星标项目"""
    if project_type == "my":
        models.Project.objects.filter(id=project_id, creator=request.tracer.user).update(star=False)
        return redirect("web:project_list")
    if project_type == "join":
        models.ProjectUser.objects.filter(project_id=project_id, creator=request.tracer.user).update(star=False)
        return redirect("web:project_list")
    return HttpResponse("请求错误")
